

package com.xgit.iov.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xgit.iov.admin.mapper.SysRoleDataRuleMapper;
import com.xgit.iov.admin.service.SysRoleDataRuleService;
import com.xgit.iov.common.core.constant.CacheConstants;
import com.xgit.iov.common.core.entity.SysRoleDataRule;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色数据权限表 服务实现类
 * </p>
 *
 * @author william
 * @since 2020/5/28
 */
@Service
@RequiredArgsConstructor
public class SysRoleDataRuleServiceImpl extends ServiceImpl<SysRoleDataRuleMapper, SysRoleDataRule> implements SysRoleDataRuleService {

	private final CacheManager cacheManager;

	/**
	 * @param role
	 * @param roleId  角色
	 * @param dataRuleIds 数据权限ID拼成的字符串，每个id之间根据逗号分隔
	 * @return
	 */

	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(value = CacheConstants.MENU_DETAILS, key = "#roleId + '_datarule'")
	public Boolean saveRoleDataRule(String role, Long roleId, String dataRuleIds) {
		this.remove(Wrappers.<SysRoleDataRule>query().lambda()
			.eq(SysRoleDataRule::getRoleId, roleId));

		if (StrUtil.isBlank(dataRuleIds)) {
			return Boolean.TRUE;
		}
		List<SysRoleDataRule> roleDataRuleList = Arrays
			.stream(dataRuleIds.split(","))
			.map(dataRuleId -> {
				SysRoleDataRule roleDataRule = new SysRoleDataRule();
				roleDataRule.setRoleId(roleId);
				roleDataRule.setDataRuleId(Long.valueOf(dataRuleId));
				return roleDataRule;
			}).collect(Collectors.toList());

		//清空数据权限
		cacheManager.getCache(CacheConstants.DATARULE_DETAILS).clear();
		return this.saveBatch(roleDataRuleList);
	}
}
